package com.cqupt.service.impl;

import com.cqupt.mapper.AuthorityTemplateMapper;
import com.cqupt.mapper.RoleMapper;
import com.cqupt.pojo.AuthorityTemplate;
import com.cqupt.pojo.Role;
import com.cqupt.pojo.RoleExample;
import com.cqupt.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AuthorityTemplateMapper authorityTemplateMapper;

    /**
     * 新增角色
     * @param role
     * @return
     */
    @Override
    public Boolean addRole(Role role) {
        /**
         * 调用数据库
         */
        Role existRole = roleMapper.selectByPrimaryKey(role.getRoleName());
        if(existRole == null) {
            int count = roleMapper.insert(role);
            if(count > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 通过角色名字获取角色
     * @param roleName
     * @return
     */
    @Override
    public Role getRoleByRoleName(String roleName) {
        Role role = roleMapper.selectByPrimaryKey(roleName);
        return role;
    }

    /**
     * 通过分页获取角色
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Role> getRoleByPageNumber(int pageNumber, int pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<Role> roleList = roleMapper.selectByExample(new RoleExample());
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        return pageInfo;
    }

    /**
     * 通过角色名字获取角色
     * @param role
     * @return
     */
    @Override
    public Boolean updateRoleByName(Role role) {
        int count = roleMapper.updateByPrimaryKeySelective(role);
        if(count > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 通过角色名字获取角色
     * @param role
     * @return
     */
    @Override
    public Boolean deleteRoleByName(Role role) {
        int count = roleMapper.deleteByPrimaryKey(role.getRoleName());
        if(count > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取角色模板
     * @return
     */
    @Override
    public String getDefaultRoleTemplate() {
        AuthorityTemplate authorityTemplate = authorityTemplateMapper.selectByPrimaryKey("default");
        return authorityTemplate.getTemplate();
    }
}
